package com.eastfair.venuebooking.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
//import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.boot.request.PageParams;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.BizException;
import com.eastfair.core.utils.ConvertUtil;
import com.eastfair.venuebooking.dao.PriceListMapper;
import com.eastfair.venuebooking.dao.PriceListSpaceMapper;
import com.eastfair.venuebooking.dto.PriceListPageQuery;
import com.eastfair.venuebooking.dto.PriceListSaveDTO;
import com.eastfair.venuebooking.dto.PriceListSpacePageQuery;
import com.eastfair.venuebooking.dto.PriceListUpdateDTO;
import com.eastfair.venuebooking.entity.Contact;
import com.eastfair.venuebooking.entity.PriceList;
import com.eastfair.venuebooking.entity.PriceListSpace;
import com.eastfair.venuebooking.entity.Space;
import com.eastfair.venuebooking.exceptioncode.VenueBookingExceptionCode;
import com.eastfair.venuebooking.service.PriceListService;
import com.eastfair.venuebooking.service.PriceListSpaceService;
import com.eastfair.venuebooking.vo.PriceListSpaceVO;
import com.eastfair.venuebooking.vo.PriceListVO;
import com.eastfair.venuebooking.vo.SpaceVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 * 价目表
 * </p>
 *
 * @author linan
 * @date 2022-06-08
 */
@Slf4j
@Service
//@DS("#thread.tenant")
public class PriceListServiceImpl extends SuperServiceImpl<PriceListMapper, PriceList> implements PriceListService {

    @Autowired
    private PriceListMapper priceListMapper;
    @Autowired
    private PriceListSpaceMapper priceListSpaceMapper;
    @Autowired
    private PriceListSpaceService priceListSpaceService;


    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<PriceList> modelList) {
        modelList.stream().forEach(s -> {
            s.setIsDeleted(BusinessConstant.YES);
        });
        // TODO: 2021/10/29 这里需要操作其他业务，如清空角色等
        return R.successDef();
    }

    @Override
    protected R<Boolean> handlerSave(PriceList model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setTenantId(ContextUtil.getTenantId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        return R.successDef();
    }


    /**
     * 查询价目列表
     *
     * @param params
     * @return
     */
    @Override
    public IPage<PriceListVO> queryPriceList(PageParams<PriceListPageQuery> params) {
        log.info("PriceListServiceImpl +++++ queryPriceList - 分页查询价目列表 params={}", JSONObject.toJSON(params));
        Page<PriceList> page = params.buildPage();  //查询展厅列表
        PriceListPageQuery pageQuery = params.getModel();
        QueryWrapper<PriceList> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(PriceList::getIsDeleted, BusinessConstant.DELETE_NO)
                .like(StrUtil.isNotBlank(pageQuery.getPriceListName()), PriceList::getPriceListName, pageQuery.getPriceListName())
                .eq(StrUtil.isNotBlank(pageQuery.getUnitCode()), PriceList::getUnitCode, pageQuery.getUnitCode())
                .between(Objects.nonNull(pageQuery.getCreateBeginTime())
                                && Objects.nonNull(pageQuery.getCreateEndTime()),
                        PriceList::getCreateTime, pageQuery.getCreateBeginTime(), pageQuery.getCreateEndTime())
                .orderByDesc(PriceList::getCreateTime);


        page = page(page, queryWrapper);

        Page<PriceListVO> priceListVOPage = ConvertUtil.convertPage(page, PriceListVO.class);

        if (Objects.nonNull(priceListVOPage.getRecords()) && priceListVOPage.getRecords().size() > 0) {
            for (PriceListVO s : priceListVOPage.getRecords()) {
                if (s.getIsEveryYear() == 1) {
                    s.setEveryYear("每年");
                    String beginTimeStr = LocalDateTimeUtil.format(s.getValidBeginTime(), "MM-dd HH:mm:ss");
                    String endTimeStr = LocalDateTimeUtil.format(s.getValidEndTime(), "MM-dd HH:mm:ss");
                    s.setBeginTimeStr(beginTimeStr);
                    s.setEndTimeStr(endTimeStr);
                }
            }


        }

        return priceListVOPage;
    }

    /**
     * 添加价目表
     *
     * @param priceListSaveDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean savePriceListInfo(PriceListSaveDTO priceListSaveDTO) {
        log.info("PriceListServiceImpl +++++ savePriceListInfo - 添加价目表 params={}", JSONObject.toJSON(priceListSaveDTO));
        PriceList priceList = BeanUtil.toBean(priceListSaveDTO, PriceList.class);
        //价目表下展厅不可为空
        if(Objects.isNull(priceListSaveDTO.getSpaceIdList()) || priceListSaveDTO.getSpaceIdList().size()==0){
            throw BizException.wrap(VenueBookingExceptionCode.IS_NULL_PRICELIST_SPACELIST);
        }

        //添加价目表信息
        this.save(priceList);
        List<Long> spaceIdList = priceListSaveDTO.getSpaceIdList();
        List<PriceListSpace> priceListSpaceList = Lists.newArrayList();
        if (spaceIdList.size() > 0) {
            for (Long s : spaceIdList) {
                PriceListSpace priceListSpace = new PriceListSpace();
                priceListSpace.setSpaceId(s);
                priceListSpace.setPriceListId(priceList.getId());
                priceListSpaceList.add(priceListSpace);
            }
            //添加展厅跟价目表的中间关联表数据
            priceListSpaceService.insertBatchPriceList(priceListSpaceList);
        }

        log.info("PriceListServiceImpl +++++ savePriceListInfo - 添加价目信息成功");
        return Boolean.TRUE;
    }

    /**
     * 修改价目表信息
     *
     * @param priceListUpdateDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updatePriceListInfo(PriceListUpdateDTO priceListUpdateDTO) {
        log.info("PriceListServiceImpl +++++ updatePriceListInfo - 修改价目表 params={}", JSONObject.toJSON(priceListUpdateDTO));
        PriceList priceList = BeanUtil.toBean(priceListUpdateDTO, PriceList.class);
        //价目表下展厅不可为空
        if(Objects.isNull(priceListUpdateDTO.getSpaceIdList()) || priceListUpdateDTO.getSpaceIdList().size()==0){
            throw BizException.wrap(VenueBookingExceptionCode.IS_NULL_PRICELIST_SPACELIST);
        }
        //修改价目表信息
        this.updateById(priceList);
        List<Long> spaceIdList = priceListUpdateDTO.getSpaceIdList();
        List<PriceListSpace> priceListSpaceList = Lists.newArrayList();
        if (spaceIdList.size() > 0) {
            for (Long s : spaceIdList) {
                PriceListSpace priceListSpace = new PriceListSpace();
                priceListSpace.setSpaceId(s);
                priceListSpace.setPriceListId(priceList.getId());
                priceListSpaceList.add(priceListSpace);
            }
            //逻辑删除价目表关联场地的信息
            priceListSpaceMapper.updateByPriceListId(priceList.getId());
            //跟新价目表关联场地的信息

            priceListSpaceService.insertBatchPriceList(priceListSpaceList);
        }
        log.info("PriceListServiceImpl +++++ savePriceListInfo - 修改价目信息成功");
        return Boolean.TRUE;
    }

    /**
     * 删除价目表信息
     *
     * @param priceListUpdateDTOList
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delPriceListByIds(List<PriceListUpdateDTO> priceListUpdateDTOList) {
        log.info("PriceListServiceImpl +++++ delPriceListById - 删除价目表 params={}", JSONObject.toJSON(priceListUpdateDTOList));
        List<PriceList> priceLists = ConvertUtil.convertList(priceListUpdateDTOList, PriceList.class);
        //获取价目表id集合
        List<Long> priceListIds = priceListUpdateDTOList.stream().map(PriceListUpdateDTO::getId).collect(Collectors.toList());
        //删除中间表数据
        priceListSpaceMapper.updateAllByPriceList(priceListIds);
        priceLists.forEach((s) -> s.setIsDeleted(1));
        this.updateBatchById(priceLists);
        log.info("PriceListServiceImpl +++++ delPriceListById - 删除价目表成功");
        return Boolean.TRUE;
    }
}
